# coding=utf-8
from decimal import Decimal
import json
from pyquery import PyQuery
from export.distributors.b2b import B2b


class Brain(B2b):
    host = 'http://www.brain.com.ua/'

    def __init__(self):
        B2b.__init__(self)

    def handlerHtmlCatalog(self, **kwargs):
        definiteCategoryName = kwargs['definiteCategoryName']
        products = {}
        if definiteCategoryName:
            self.browser.open(self.host)
            jQuery = PyQuery(self.browser.response().get_data())
            categories = jQuery('div .menu_popap a')
            for category in categories:
                if unicode(category.text.encode('utf-8'), 'utf-8').lower() == unicode(
                        definiteCategoryName.encode('utf-8'), 'utf-8').lower():
                    products = self.proccessRule(
                        {definiteCategoryName: self.handlerHtmlCategory(url=category.attrib['href'], numb=0)})
        return products

    def handlerHtmlCategory(self, **kwargs):
        products = []
        numb = kwargs['numb']
        url_ = kwargs['url']
        url = self.getCategoryProductsPriceUrl(url_.split('category/')[1].replace('/', ''), numb)
        products_ = json.loads(self.browser.open(url).get_data(), encoding='utf-8')['products']
        if products_:
            for product_ in products_:
                product = self.handlerHtmlProduct(product_=product_)
                if product:
                    products.append(product)
            products_ = self.handlerHtmlCategory(url=url_, numb=numb + 1)
            if products_:
                products += products_
        return products

    def handlerHtmlProduct(self, **kwargs):
        product_ = kwargs['product_']
        if not product_.has_key('ProductCode'):
            return None
        sku = product_['ProductCode']
        product = {'sku': sku, 'name': product_['NameRu'], 'descr': product_['DescriptionRu'],
                   'short_descr': product_['BriefDescriptionRu']}
        if self.checkProduct(sku, 1):
            product['price'] = self.getProductPriceBySKu(sku)
        else:
            product['price'] = Decimal(product_['Price'])
        self.browser.open(self.host + '%s.html' % product_['Slug'])
        jQuery = PyQuery(self.browser.response().get_data())
        attrs = {}
        attrs_ = jQuery('div .features_block table').children()[1:]
        attrs_ = attrs_[:len(attrs_) - 1]
        for attr_ in attrs_:
            key, value = jQuery(attr_).children()
            attrs[key.text] = value.text
        product['attrs'] = attrs
        return product


    def getCategoryProductsPriceUrl(self, categoryName, page):
        return 'http://brain.com.ua/product_list?page=%s&search_text=&category=%s&vendor=0&filter=&order=' % (
            page, categoryName)
